package hust.rpc.proxy;

import javafx.util.Pair;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public abstract class Proxy {

    protected final Map<Class<?>, Object> invokerMappings = new HashMap<>();
    protected final List<String> remoteServices = new ArrayList<>();
    protected final List<String> localServices = new ArrayList<>();

    /**
     * 初始化服务接口
     *
     * @param services 服务接口集合
     */
    public void initProxy(Set<Class<?>> services) {
        for (Class<?> service : services) {
            if (service.isInterface()) {
                remoteServices.add(service.getTypeName());
            } else {
                for (Class<?> serviceIf : service.getInterfaces()) {
                    localServices.add(serviceIf.getTypeName());
                }
            }
            getProxy(service);
        }
    }

    @SuppressWarnings("unchecked")
    public <T> T getProxy(Class<T> clazz) {
        // 校验
        Objects.requireNonNull(clazz, "接口类不得为空!");
        if (invokerMappings.containsKey(clazz)) return (T) invokerMappings.get(clazz);
        T internalProxy = getInternalProxy(clazz);
        if (clazz.isInterface()) {
            invokerMappings.put(clazz, internalProxy);
        } else {
            for (Class<?> service : clazz.getInterfaces()) {
                invokerMappings.put(service, internalProxy);
            }
        }
        return internalProxy;
    }

    protected abstract <T> T getInternalProxy(Class<T> clazz);

    protected Pair<Method, Object> getProxy(String signature) {
        return null;
    }

    public Object invoke(String signature, Object[] args) throws InvocationTargetException, IllegalAccessException {
        return null;
    }

    public List<String> getRemoteServices() {
        return remoteServices;
    }

    public List<String> getLocalServices() {
        return localServices;
    }
}
